package com.atguigu.daijia.driver.service.impl;

import com.atguigu.daijia.common.execption.GuiguException;
import com.atguigu.daijia.common.result.ResultCodeEnum;
import com.atguigu.daijia.driver.config.TencentCloudProperties;
import com.atguigu.daijia.driver.mapper.DriverInfoMapper;
import com.atguigu.daijia.driver.service.CiService;
import com.atguigu.daijia.driver.service.CosService;
import com.atguigu.daijia.model.vo.driver.CosUploadVo;
import com.mysql.cj.util.StringUtils;
import com.qcloud.cos.COSClient;
import com.qcloud.cos.ClientConfig;
import com.qcloud.cos.auth.BasicCOSCredentials;
import com.qcloud.cos.auth.COSCredentials;
import com.qcloud.cos.http.HttpMethodName;
import com.qcloud.cos.http.HttpProtocol;
import com.qcloud.cos.model.*;
import com.qcloud.cos.region.Region;
import jakarta.annotation.Resource;
import lombok.extern.slf4j.Slf4j;
import org.joda.time.DateTime;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.net.URL;
import java.util.Date;
import java.util.UUID;

@Slf4j
@Service
@SuppressWarnings({"unchecked", "rawtypes"})
public class CosServiceImpl implements CosService {

    @Resource
    private TencentCloudProperties tencentCloudProperties;
    @Resource
    private DriverInfoMapper driverInfoMapper;
    @Resource
    private CiService ciService;
    @Override
    /**
     * 上传文件到腾讯云COS
     *
     * @param file 待上传的文件
     * @param path 上传文件的路径
     * @return 返回上传后的文件信息，包括URL等
     */
    public CosUploadVo upload(MultipartFile file, String path) {
        // 获取COS客户端实例
        COSClient cosClient = getCosClient();
        // 创建对象元数据
        ObjectMetadata meta = new ObjectMetadata();
        // 设置文件大小
        meta.setContentLength(file.getSize());
        // 设置文件编码
        meta.setContentEncoding("UTF-8");
        // 设置文件类型
        meta.setContentType(file.getContentType());

        // 获取文件扩展名
        String fileType = file.getOriginalFilename().substring(file.getOriginalFilename().lastIndexOf("."));
        // 生成上传后的文件路径，包括文件名和扩展名
        String uploadPath = "/driver/" + path + "/" +
                UUID.randomUUID().toString().replaceAll("-", "") + fileType;
        // 创建上传请求
        PutObjectRequest putObjectRequest = null;
        try {
            // 初始化上传请求，指定存储桶、上传路径、文件输入流和元数据
            putObjectRequest = new PutObjectRequest(tencentCloudProperties.getBucketPrivate(),
                    uploadPath, file.getInputStream(),meta);
            // 设置存储类型为标准存储
            putObjectRequest.setStorageClass(StorageClass.Standard);
        }catch (Exception e){
            e.printStackTrace();
        }
        // 执行上传操作，返回上传结果
        PutObjectResult putObjectResult = cosClient.putObject(putObjectRequest);
        cosClient.shutdown();
        Boolean isAuditing = ciService.imageAuditing(uploadPath);
        if(!isAuditing){
            cosClient.deleteObject(tencentCloudProperties.getBucketPrivate(),uploadPath);
            throw new GuiguException(ResultCodeEnum.IMAGE_AUDITION_FAIL);
        }

        // 创建上传后的文件信息对象
        CosUploadVo cosUploadVo = new CosUploadVo();
        cosUploadVo.setUrl(uploadPath);
        cosUploadVo.setShowUrl(getImageUrl(uploadPath));

        return cosUploadVo;


    }

    @Override
    public String getImageUrl(String path) {
        if(StringUtils.isNullOrEmpty(path)){
            return "";
        }
        COSClient cosClient = getCosClient();
        GeneratePresignedUrlRequest request = new GeneratePresignedUrlRequest(tencentCloudProperties.getBucketPrivate(), path,
                HttpMethodName.GET);
        Date exception = new DateTime().plusMillis(15).toDate();
        request.setExpiration(exception);
        URL url = cosClient.generatePresignedUrl(request);
        return url.toString();
    }

    private COSClient getCosClient() {
        COSCredentials cred = new BasicCOSCredentials(tencentCloudProperties.getSecretId(),
                tencentCloudProperties.getSecretKey());
        Region region = new Region(tencentCloudProperties.getRegion());
        ClientConfig clientConfig = new ClientConfig(region);
        clientConfig.setHttpProtocol(HttpProtocol.https);
        return new COSClient(cred, clientConfig);
    }
}
